<template>
  <div class="cancel-booking-page">
    <h2>取消预订</h2>

    <div v-if="loading" class="loading-spinner">加载中...</div>
    <div v-if="error" class="error-message">{{ error }}</div>
    <div v-if="successMessage" class="success-message">{{ successMessage }}</div>

    <section class="refund-policy-section">
      <h3>取消退费规则</h3>
      <ul>
        <li v-for="rule in refundPolicy" :key="rule.hours_before_start">
          {{ rule.description }}
        </li>
      </ul>
    </section>

    <section class="cancellable-bookings-section">
      <h3>可申请取消的预订</h3>
      <p v-if="cancellableBookings.length === 0 && !loading">
        目前没有符合取消条件的预订。
      </p>
      <div v-else class="booking-list">
        <div v-for="booking in cancellableBookings" :key="booking.order_id" class="booking-item">
          <div class="booking-details">
            <p><strong>订单ID:</strong> {{ booking.order_id }}</p>
            <p><strong>会议室:</strong> {{ booking.room_name }}</p>
            <p><strong>预订时间:</strong> {{ booking.start_time }} - {{ booking.end_time }}</p>
            <p><strong>总金额:</strong> ¥{{ booking.total_fee }}</p>
          </div>
          <button @click="handleCancelBooking(booking.order_id)" class="cancel-button">
            申请取消
          </button>
        </div>
      </div>
    </section>

    <section class="cancellation-requests-section">
      <h3>我的取消申请状态</h3>
      <p v-if="cancellationRequests.length === 0 && !loading">
        您目前没有提交的取消申请。
      </p>
      <div v-else class="request-list">
        <div v-for="request in cancellationRequests" :key="request.order_id" class="request-item">
          <div class="request-details">
            <p><strong>订单ID:</strong> {{ request.order_id }}</p>
            <p><strong>会议室:</strong> {{ request.room_name }}</p>
            <p><strong>预订时间:</strong> {{ request.start_time }} - {{ request.end_time }}</p>
            <p><strong>总金额:</strong> ¥{{ request.total_fee }}</p>
            <p><strong>预估退款:</strong> ¥{{ request.refund_fee.toFixed(2) }}</p>
            <p><strong>申请时间:</strong> {{ request.cancel_time }}</p>
            <p><strong>状态:</strong>
              <span :class="getStatusClass(request.cancellation_status)">
                {{ getStatusText(request.cancellation_status) }}
              </span>
            </p>
          </div>
          <div class="request-actions" v-if="request.cancellation_status === 2">
            <button @click="handleConfirmCancellation(request.order_id)" class="confirm-button">
              确认取消完成
            </button>
          </div>
        </div>
      </div>
    </section>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router'; // Import useRoute and useRouter
import { useAuthStore } from '../../stores/auth.js';
import { fetchRefundPolicy, fetchAllBookings, cancelBooking, confirmCancellationCompletion } from '../../mocks/clientApi.js'; // Import confirmCancellationCompletion

const route = useRoute(); // Initialize route
const router = useRouter(); // Initialize router

const authStore = useAuthStore();
const refundPolicy = ref([]);
const cancellableBookings = ref([]);
const cancellationRequests = ref([]);
const loading = ref(false);
const error = ref(null);
const successMessage = ref(null);
const selectedOrderId = ref(null); // To store orderId from query parameter

// Helper to parse date strings
const parseDateTime = (dtString) => new Date(dtString.replace(' ', 'T'));

const fetchCancellationData = async () => {
  loading.value = true;
  error.value = null;
  successMessage.value = null;
  try {
    const userId = authStore.user ? authStore.user.user_id : null;
    if (!userId) {
      error.value = '用户未登录或用户信息不完整。';
      loading.value = false; // Ensure loading is set to false on error
      return;
    }

    // Check for orderId in query parameter
    if (route.query.orderId) {
      selectedOrderId.value = parseInt(route.query.orderId);
      console.log('Navigated to CancelBookingPage with orderId:', selectedOrderId.value);
      // Optionally, clear the query parameter after processing
      router.replace({ query: null });
    }

    const policyResponse = await fetchRefundPolicy();
    if (policyResponse.success) {
      refundPolicy.value = policyResponse.data;
    } else {
      error.value = policyResponse.message || '获取退费规则失败。';
    }

    const allBookingsResponse = await fetchAllBookings(userId); // Fetch all bookings
    if (allBookingsResponse.success) {
      const now = new Date();
      const twentyFourHoursLater = new Date(now.getTime() + 24 * 60 * 60 * 1000);

      cancellableBookings.value = allBookingsResponse.data.filter(
        (booking) =>
          booking.status === 1 && // Valid order
          booking.payment_status === 2 && // Paid
          booking.cancellation_status === 0 && // Not yet requested cancellation
          parseDateTime(booking.start_time) > twentyFourHoursLater // Start time is more than 24 hours in the future
      );

      cancellationRequests.value = allBookingsResponse.data.filter(
        (booking) => booking.cancellation_status !== 0 // Has a cancellation status (pending, approved, rejected)
      );
    } else {
      error.value = allBookingsResponse.message || '获取预订列表失败。';
    }
  } catch (err) {
    console.error('Error fetching cancellation data:', err);
    error.value = '加载数据时发生错误。';
  } finally {
    loading.value = false;
  }
};

const handleCancelBooking = async (orderId) => {
  if (!confirm('您确定要申请取消此预订吗？申请提交后将等待员工审核，并根据规则计算退款金额。')) {
    return;
  }

  loading.value = true;
  error.value = null;
  successMessage.value = null;
  try {
    const userId = authStore.user.user_id;
    const result = await cancelBooking(orderId, userId);
    if (result.success) {
      successMessage.value = result.message;
      // Re-fetch data to update both lists
      await fetchCancellationData();
    } else {
      error.value = result.message || '取消预订申请失败。';
    }
  } catch (err) {
    console.error('Error submitting cancellation request:', err);
    error.value = '提交取消预订申请时发生错误。';
  } finally {
    loading.value = false;
  }
};

const handleConfirmCancellation = async (orderId) => {
  if (!confirm('您确定要确认此取消预订已完成吗？')) {
    return;
  }

  loading.value = true;
  error.value = null;
  successMessage.value = null;
  try {
    const result = await confirmCancellationCompletion(orderId, userId);
    if (result.success) {
      successMessage.value = result.message;
      await fetchCancellationData(); // Re-fetch data to update lists
    } else {
      error.value = result.message || '确认取消完成失败。';
    }
  } catch (err) {
    console.error('Error confirming cancellation:', err);
    error.value = '确认取消完成时发生错误。';
  } finally {
    loading.value = false;
  }
};

const getStatusText = (status) => {
  switch (status) {
    case 1: return '待审核';
    case 2: return '已批准 (待确认)';
    case 3: return '已拒绝';
    case 0: return '未申请'; // Should not appear in requests list, but for completeness
    default: return '未知状态';
  }
};

const getStatusClass = (status) => {
  switch (status) {
    case 1: return 'status-pending';
    case 2: return 'status-approved';
    case 3: return 'status-rejected';
    default: return '';
  }
};

onMounted(fetchCancellationData);
</script>

<style scoped>
.cancel-booking-page {
  padding: 2rem;
  max-width: 800px;
  margin: 0 auto;
  font-family: 'Arial', sans-serif;
}

h2, h3 {
  color: #333;
  margin-bottom: 1rem;
}

.loading-spinner, .error-message, .success-message {
  padding: 1rem;
  margin-bottom: 1rem;
  border-radius: 4px;
  text-align: center;
}

.loading-spinner {
  background-color: #e0f7fa;
  color: #00796b;
}

.error-message {
  background-color: #ffebee;
  color: #c62828;
}

.success-message {
  background-color: #e8f5e9;
  color: #2e7d32;
}

.refund-policy-section, .cancellable-bookings-section, .cancellation-requests-section {
  background-color: #f9f9f9;
  border: 1px solid #eee;
  border-radius: 8px;
  padding: 1.5rem;
  margin-bottom: 2rem;
}

.refund-policy-section ul {
  list-style: disc;
  padding-left: 1.5rem;
}

.refund-policy-section li {
  margin-bottom: 0.5rem;
  color: #555;
}

.booking-list, .request-list {
  display: grid;
  gap: 1rem;
}

.booking-item, .request-item {
  background-color: #fff;
  border: 1px solid #ddd;
  border-radius: 8px;
  padding: 1rem;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.booking-details, .request-details {
  flex-grow: 1;
}

.booking-details p, .request-details p {
  margin: 0.3rem 0;
  color: #444;
}

.booking-details strong, .request-details strong {
  color: #222;
}

.cancel-button {
  background-color: #f44336;
  color: white;
  border: none;
  padding: 0.75rem 1.25rem;
  border-radius: 5px;
  cursor: pointer;
  font-size: 1rem;
  transition: background-color 0.3s ease;
}

.cancel-button:hover {
  background-color: #d32f2f;
}

.cancel-button:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

.request-actions button {
  margin-left: 0.5rem;
  padding: 0.75rem 1.25rem;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  font-size: 1rem;
  transition: background-color 0.3s ease;
}

.confirm-button {
  background-color: #2196F3; /* Blue */
  color: white;
}

.confirm-button:hover {
  background-color: #1976D2;
}

.status-pending {
  color: #FF9800; /* Orange */
  font-weight: bold;
}

.status-approved {
  color: #4CAF50; /* Green */
  font-weight: bold;
}

.status-rejected {
  color: #F44336; /* Red */
  font-weight: bold;
}
</style>
